package com.ezjie.ielts.service;

import java.io.File;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.widget.RemoteViews;

import com.ezjie.ielts.R;
import com.ezjie.ielts.model.UpdateDetail;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

/**
 * 更新完成 安装的服务，否则退出应用，下载完后 无法安装。
 * 
 */
public class UpdateCompleteService extends Service {

	private HttpUtils hUtils;
	private NotificationManager nm;
	private Notification notification;
	private int notifyflag = 1;
	private HttpHandler handler;

	// private String url = "http://198.11.172.44/apk/ToeflEzjie.apk";

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		UpdateDetail detail = (UpdateDetail) intent.getSerializableExtra("update");
		// 查找 文件名
		String fileName = Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + "_"
				+ "EasyApp_ezjie.apk";
		// 加上这个参数，可以解决获取文件长度为-1的问题
		RequestParams requestParams = new RequestParams();
		requestParams.addHeader("Accept-Encoding", "identity");

		handler = hUtils.download(detail.url, fileName, requestParams, true, true, new RequestCallBack<File>() {
			@Override
			public void onStart() {
				nm.notify(notifyflag, notification);
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				nm.cancel(notifyflag);
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				RemoteViews contentView1 = notification.contentView;
				contentView1.setProgressBar(R.id.n_progress, 100, (int) (current * 100 / total), false);
				contentView1.setTextViewText(R.id.n_text, getString(R.string.app_name) + "   " + (int) (current * 100 / total) + "%");
				notification.contentView = contentView1;
				// 提交一个通知在状态栏中显示。如果拥有相同标签和相同id的通知已经被提交而且没有被移除，该方法会用更新的信息来替换之前的通知。
				nm.notify(notifyflag, notification);
			}

			@Override
			public void onSuccess(ResponseInfo<File> arg0) {
				nm.cancel(notifyflag);
				Uri uri = Uri.fromFile(arg0.result);
				openfile(uri);
			}
		});
	}

	@Override
	public void onCreate() {
		super.onCreate();
		hUtils = new HttpUtils();
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		// 创建Notifcation对象，设置图标，提示文字
		notification = new Notification(R.drawable.ic_launcher, getString(R.string.app_name),
				System.currentTimeMillis());
		notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
		RemoteViews view = new RemoteViews(getPackageName(), R.layout.notification_down_update);
		view.setProgressBar(R.id.n_progress, 100, 0, false);
		notification.contentView = view;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		nm.cancel(notifyflag);
		handler.cancel();
	}

	public void openfile(Uri uri) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		// 区别于默认优先启动在activity栈中已经存在的activity（如果之前启动过，并还没有被destroy的话）而是无论是否存在，都重新启动新的activity
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		startActivity(intent);
	}

}
